package logic

import (
	"context"

	a "godco/internal/model/auth"
	"godco/internal/svc"
	"godco/internal/types"
	"godco/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type OAuth2CallBackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

var TokenUrl = "https://api.atomgit.com/login/oauth/access_token"

func NewOAuth2CallBackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OAuth2CallBackLogic {
	return &OAuth2CallBackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OAuth2CallBackLogic) OAuth2CallBack(req *types.CallBackReq) (resp *types.CallBackResp, err error) {
	// todo: add your logic here and delete this line
	l.Debugf("Code:%s", req.Code)
	l.Debugf("Install_id:%s", req.Install)
	l.Debugf("State:%s", req.State)
	l.Debugf("Email:%s", req.Email)

	ret := types.CallBackResp{Code: 0, Message: "授权成功!"}
	// 使用code向AtomGit的令牌端点请求访问令牌
	tokenResp, err := utils.GetToken(TokenUrl, l.svcCtx.Config.Client.ClientID, l.svcCtx.Config.Client.ClientSecret, req.Code)
	if err != nil {
		l.Error(err)
		ret.Code = 400
		ret.Message = err.Error()
		return &ret, err
	}

	l.Debugf("Access Token: %s", tokenResp.AccessToken)
	l.Debugf("Refresh Token: %s", tokenResp.RefreshToken)
	// 获取用户个人信息
	info, err := utils.GetUserInfo(tokenResp.AccessToken)
	if err == nil {
		l.Debugf("GetUserInfo ok,userID: %s", info.UID)
	} else {
		l.Error(err)
		ret.Code = 400
		ret.Message = err.Error()
		return &ret, err
	}
	// token入库
	data_, err := l.svcCtx.AuthModel.FindOneByInstallID(l.ctx, req.Install)
	if err == a.ErrNotFound {
		data := a.Auth{UID: info.UID, IID: req.Install, Name: info.Name, Login: info.Login, Email: info.Email, Phone: info.Phone, Token: tokenResp.AccessToken, TokenF: tokenResp.RefreshToken}
		err = l.svcCtx.AuthModel.Insert(l.ctx, &data)
		if err != nil {
			resp = &types.CallBackResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
		l.Debug("token入库成功")
	} else {
		data_.Token = tokenResp.AccessToken
		data_.TokenF = tokenResp.RefreshToken
		data_.UID = info.UID
		data_.Email = info.Email
		data_.Name = info.Name
		data_.Phone = info.Phone
		_, err = l.svcCtx.AuthModel.Update(l.ctx, data_)
		if err != nil {
			resp = &types.CallBackResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
		l.Debug("token更新成功")
	}

	return &ret, nil
}
